<template>
  <div class="multiPictureUpload">
    <div v-if="props.listType == 'picture-card'" class="middle-box">
      <draggable :list="arr1" ghost-class="eghost" handle=".move" filter=".forbid" :force-fallback="true"
        chosen-class="chosenClass" animation="300" @start="onStart" @end="onEnd" sort="true" :fallback-class="true"
        dragClass="dragClass" :fallback-on-body="true" :touch-start-threshold="50" :fallback-tolerance="50" :move="onMove"
        group="itxst" class="drag-box">
        <template #item="{ element }">
          <div class="uploadList move">
            <!-- <div class="edit-item uploadList"> -->
            <img class="imgList" :src="element.url" />
            <!-- <a-progress :percent="pp" size="small" /> -->
            <div class="uploadList-mask">
              <a-tooltip>
                <template #title>图片裁剪</template>
                <span class="iconfont icon-cutting" @click="handleCropper(element)"></span>
              </a-tooltip>
              <a-tooltip>
                <template #title>图片预览</template>
                <span class="iconfont icon-preview" @click="handlePreview(element)"></span>
              </a-tooltip>
              <a-tooltip>
                <template #title>图片删除</template>
                <span class="iconfont" @click="removePictrues(element)">&#xe8e2;</span>
              </a-tooltip>
            </div>
            <!-- </div> -->
          </div>
        </template>
      </draggable>
    </div>
    <a-upload class="avatar-uploader" :accept="props.accept" :directory="props.directory" :listType="props.listType"
      :maxCount="props.maxCount" :multiple="props.multiple" :progress="progress" :isLimit="props.isLimit"
      @preview="handlePreview" :before-upload="beforeUpload" :custom-request="(file: otherType) => handleUpload(file)"
      :show-upload-list="true" :headers="{ authorization: 'authorization-text' }">
      <div v-if="props.listType == 'text'">
        <a-button class="upload_button_line" :disabled="fileList.length >= props.maxCount"
          v-if="props.listType == 'text'">
          <upload-outlined></upload-outlined>
          {{ props.title }}
          <div class="suggest" v-if="props.imgSuggest">
            {{ props.imgSuggest }}
          </div>
        </a-button>
        <div class="tips" v-if="props.accept">支持{{ props.accept }}格式</div>
      </div>

      <div v-show="props.listType == 'picture-card'">
        <plus-outlined />
        <span class="iconfont icon-Add"></span>
        <div class="ant-upload-text">{{ props.title }}</div>
        <div class="suggest" v-if="props.imgSuggest">
          {{ props.imgSuggest }}
        </div>
      </div>
    </a-upload>
    <base-modal :width="modAlProps.width" :isVisible="previewVisible" :title="previewTitle" :isCancleBtn="false"
      :buttons="buttons" @handleCancle="previewVisible = false" class="upload_modal">
      <template v-slot:body>
        <img alt="previewImage" :style="styles" :src="previewImage" />
      </template>
    </base-modal>
    <cropper :isVisible="cropper_isVisible" :src="fileObj.url" :id="fileObj.id" @handleOk="handleOk"
      @handleCancle="cropper_isVisible = false" v-if="props.fileList.length"></cropper>
  </div>
</template>
<script lang="ts" setup>
import { ref, watch, computed, nextTick, onMounted, reactive } from "vue";
import baseModal from "@/components/modal/baseModal.vue";
import cropper from "./oldCropper.vue";
import { message } from "ant-design-vue";
import { MultipleUploadProps } from "./uploadConfig/props";
import { dataSourceType } from "../../type";
import { request } from "@/api/axios";
import draggable from "vuedraggable";
import {
  comps,
  configSetting,
  formConfigSetting,
} from "@/components/draggable/exportComp";
//import request from "@/api/index";
function getBase64(file: File) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = (error) => reject(error);
  });
}
//props
const props = defineProps(MultipleUploadProps);

//emit
const emit = defineEmits([
  "uploadChangeFinished",
  "uploadFinished",
  "upload_remove_Finished",
  'cutFinished',
]);
//type
type otherType = {
  [propName: string]: any;
};
//data
const previewVisible = ref<Boolean>(false);
const previewImage = ref<string>("");
const previewTitle = ref<string>("");
const fileList = ref<any>([]);
const fileObj = ref<any>([]);
let acceptTypeList = ref<string[]>([]);
let styles = ref<string>("");
const arr1 = ref(props.fileList);
//模态框
const modAlProps = reactive({
  width: "M",
  title: "",
});
const cropper_isVisible = ref<Boolean | any>(false);
const progress = reactive({
  // 重写进度条
  strokeColor: {
    "0%": "#1890FF",
    "100%": "#1890FF",
  },
  strokeWidth: 2,
  format: (percent = 0) => {
    return `${parseFloat((+percent).toFixed(0))}%`;
  },
  class: "test",
  style: { width: "95%", fontSize: "12px" },
});
const pp = ref<string | number>(0);
const buttons = ref<dataSourceType[]>([]); //模态框button按钮个数和文案修改
//watch
watch(
  () => props.fileList,
  (newVal, oldVal) => {
    console.log(newVal, '多图')
    // if (newVal.length) {
    //   fileList.value = newVal;
    //   fileList.value.map((item: any, index: any) => {
    //     console.log(item, "item");
    //     getImageStyle(item.url, index);
    //   });
    // } else {
    //   fileList.value = [];
    // }
    arr1.value = newVal;
  },
  { deep: true, immediate: true }
);
//methods
const getImageStyle = (src: string, index: number) => {
  const url = src;
  if (url) {
    var img = new Image();
    img.src = url;
    img.onload = function () {
      console.log(img.naturalWidth, img.naturalHeight, 9999);
      if (img.naturalWidth >= img.naturalHeight) {
        fileList.value[index].styles = `width:100%;height:auto`;
        styles.value = `width:100%;height:auto`;
      } else {
        fileList.value[index].styles = `width:auto;height:100%`;
        styles.value = `width:auto;height:100%`;
      }
    };
  }
};
//// 删除图片
const removePictrues = (info: any) => {
  //
  emit("upload_remove_Finished", info);
};
const beforeUpload = (file: otherType["fileList"][number]) => {
  console.log(file, "file");
  // 文件上传之前的限制条件过滤，有文件类型和文件大小限制。
  return new Promise((resolve, reject) => {
    // beforeUpload必须使用promise 返回false才能阻止change事件，否则无效
    const backgFix = file.name.substring(file.name.lastIndexOf(".") + 1); //获取文件的后缀
    let isFileType = true;
    if (acceptTypeList.value.length) {
      isFileType = acceptTypeList.value.includes(backgFix);

      if (!isFileType) {
        message.error(`只能上传${acceptTypeList.value.join(",")}格式文件!`);
        return false;
      }
    }

    let isLt2M = true;
    if (props.isLimit) {
      isLt2M =
        props.isLimit == 0 ? true : file.size / 1024 / 1024 < props.isLimit;
      if (!isLt2M) {
        message.error(`文件大小不得超过 ${props.isLimit} MB!`);
        return false;
      }
    }

    if (isFileType && isLt2M) {
      //fileList.value = [...fileList.value, file]
      return resolve(true);
    }
  });
};

const handleUpload = (options: otherType) => {
  // 上传到服务器
  const param = new FormData(); // 创建form对象
  param.append("files", options.file, options.file.name); // 通过append向form对象添加数据

  if (props.isAutoUpload) {
    // props.isAutoUpload 用来判断是否能直接上传，若不能，需要用emit传递出formData数据到调取处

    options.file.status = "success";
    request
      .post("/server-admin/res/upload", param, {
        headers: {
          "Content-Type":
            "multipart/form-data; boundary=----WebKitFormBoundary1kBB8pgsKICPa9RM",
        },
        onUploadProgress: ({ total, loaded }) => {
          if (total) {
            pp.value =
              Math.round((loaded / total) * 100) < 100
                ? Math.round((loaded / total) * 100).toFixed(1)
                : (100 - Math.random() * 10).toFixed(1); //留足大图片渲染时间
            if (options.onProgress) {
              //留足大图片渲染时间
              options.onProgress(
                { percent: Math.round((loaded / total) * 100).toFixed(2) },
                options
              );
            }
          }
        },
      })
      .then((res: any) => {
        if (res.data.code == "00000 00000") {
          if (options.cutId) {
            emit('cutFinished', res.data.data, options.cutId);
          } else {
            emit("uploadFinished", res.data.data, options.id);
          }
          pp.value = 100;
          if (options.onSuccess) {
            options.onSuccess(res.data.data, options);
          }




          message.success(res.data.message);
        } else {
          message.error(res.data.message);
          if (options.onError) {
            options.onError(res.data.data, options);
          }

          fileList.value = [];
        }
      })
      .catch((err) => {
        console.log(err, 9999);
      });
  } else {
    emit("uploadChangeFinished", options);
  }
};

const handlePreview = async (file: otherType["fileList"][number]) => {
  // 文件预览
  if (!file.url && !file.preview) {
    file.preview = (await getBase64(file.originFileObj)) as string;
  }
  previewImage.value = file.url || file.preview;
  previewVisible.value = true;
  previewTitle.value =
  file.oriFileName || file.name || file.file.name || file.url.substring(file.url.lastIndexOf("/") + 1);
};
const onMove = (e: any, item: any) => {
  console.log(e, item, "tttttt");
};
const onStart = (e: any) => {
  console.log(e, "开始拖拽");
};
//拖拽结束的事件
const onEnd = (e: any) => {
  console.log(e, 88129392);
  console.log(fileList.value, "11111");
};
const handleCropper = async (file: otherType) => {
  fileObj.value = file;
  cropper_isVisible.value = true;
};
const handleOk = (content: object, id: string, e: object) => {
  cropper_isVisible.value = false;
  let filess = {
    file: content,
    id: id,
    cutId: id,
  };
  handleUpload(filess);
};
// computed
acceptTypeList = computed({
  get() {
    return props.accept ? props.accept.split(",") : [];
  },
  set() { },
});
</script>
<style lang="scss" scoped>
.upload_button_line {
  margin-bottom: 4px;
}

.suggest {
  font-size: 12px;
  font-family: PingFang SC-Regular, PingFang SC;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.85);
  line-height: 20px;
}

.tips {
  font-weight: 400;
  color: rgba(0, 0, 0, 0.45);
  font-size: 12px;
}

.iconfont.icon-Add {
  font-size: 24px;
  color: rgba(0, 0, 0, 0.85);
}

.drag-box {
  // display: flex;
  // flex-direction: row;
  // flex-wrap: wrap;
  // align-items: center;
  // justify-content: space-between;

  .uploadList {
    display: inline-block;
    width: 104px;
    height: 104px;
    margin-right: 8px;
    margin-bottom: 8px;
    text-align: center;
    vertical-align: top;
    background-color: #fafafa;
    border: 1px dashed #d9d9d9;
    border-radius: 2px;
    cursor: default;
    transition: border-color 0.3s;
    position: relative;
    padding: 8px;
    // display: flex;
    align-items: center;

    .imgList {
      max-width: 88px;
      max-height: 88px;
    }

    .uploadList-mask {
      background-color: rgba(0, 0, 0, 0.5);
      width: 88px;
      height: 88px;
      margin: 8px;
      box-sizing: border-box;
      position: absolute;
      top: 0;
      left: 0;
      align-items: center;
      justify-content: center;
      display: none;
      z-index: 950;

      .iconfont {
        width: 23px;
        color: rgba(255, 255, 255, 0.8);

      }

      .iconfont:hover {
        color: rgba(255, 255, 255, 1);
        cursor: pointer;
      }

      .icon-delete {
        margin-left: 0;
      }
    }

    .uploadList-mask:hover {
      display: flex;
    }
  }

  .column-system {
    width: 224px;
  }

  .uploadList:hover {
    border: 1px dashed #1f6ded;
    cursor: move;

    .text {
      color: #1f6ded;
    }

    .drag-icon {
      color: #1f6ded;
    }
  }
}

.uploadList:hover {
  .uploadList-mask {
    display: flex;
  }
}

// .group {
//   display: flex;
//   flex-direction: column;
//   justify-content: flex-start;
//   align-content: center;
//   width: 32%;
//   margin-right: 20px;
// }
.dragClass {
  display: flex;
  width: 104px;
  height: 104px;
  padding: 8px;
  background-color: #fafafa;
  border: 1px dashed #d9d9d9;
  border-radius: 2px;
}

.chosenClass {
  height: max-content;
  width: max-content;
  // padding: 8px;
  display: flex;
  box-sizing: border-box;

  // border: 1px solid #1ec6df;
  .uploadList-mask {
    display: none;
  }
}
</style>
<style lang="scss">
.multiPictureUpload {
  .ant-progress-line {
    width: 78px;
    position: absolute;
    left: 12px;
    top: 43px;

    .ant-progress-bg {
      height: 2px !important;
    }
  }

  .ant-progress-status-success {
    display: none;
  }

  .ant-upload-list-picture-card-container {
    display: none;
  }
}
</style>
